
package com.yami.shop.discount.platform.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.OfflineHandleEventType;
import com.yami.shop.bean.enums.SendType;
import com.yami.shop.bean.event.SendMessageEvent;
import com.yami.shop.bean.model.OfflineHandleEvent;
import com.yami.shop.bean.param.NotifyTemplateParam;
import com.yami.shop.bean.param.OfflineHandleEventAuditParam;
import com.yami.shop.common.enums.StatusEnum;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.discount.common.model.Discount;
import com.yami.shop.discount.common.model.DiscountProd;
import com.yami.shop.discount.common.service.DiscountService;
import com.yami.shop.security.platform.util.SecurityUtils;
import com.yami.shop.service.OfflineHandleEventService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author yami
 */
@RestController
@RequestMapping("/platform/discount")
@Tag(name = "平台端端促销活动接口")
public class DiscountController {

    @Autowired
    private DiscountService discountService;
    @Autowired
    private OfflineHandleEventService offlineHandleEventService;
    @Autowired
    private  ApplicationEventPublisher eventPublisher;

    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('platform:discount:page')")
    @Operation(summary =  "分页获取促销活动列表信息")
    public ServerResponseEntity<IPage<Discount>> page(@ParameterObject Discount discount, PageParam<Discount> page) {
        IPage<Discount> discountPage = discountService.getPlatformDiscountPage(page, discount);
        return ServerResponseEntity.success(discountPage);
    }

    @GetMapping("/info/{discountId}")
    @Operation(summary =  "根据活动id获取促销活动信息")
    @Parameter(name = "discountId", description = "活动ID", required = true)
    @PreAuthorize("@pms.hasPermission('platform:discount:info')")
    public ServerResponseEntity<Discount> info(@PathVariable("discountId") Long discountId) {
        Discount discount = discountService.getDiscountAndItemAndProdById(discountId);
        if (discount == null) {
            // 未找到此活动信息
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        // 在折扣商品列表中去掉已经删除的商品
        List<DiscountProd> discountProdList = discount.getDiscountProds().stream().filter(discountProd -> !Objects.equals(discountProd.getProdStatus(), StatusEnum.DELETE.value())).collect(Collectors.toList());
        discount.setDiscountProds(discountProdList);
        return ServerResponseEntity.success(discount);
    }

    @PostMapping("/offline")
    @PreAuthorize("@pms.hasPermission('platform:discount:update')")
    @Operation(summary =  "下线活动")
    public ServerResponseEntity<Void> offline(@RequestBody OfflineHandleEvent offlineHandleEvent) {
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        Discount discount = discountService.getById(offlineHandleEvent.getHandleId());
        if (discount == null) {
            // 未找到此活动信息
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        discountService.offline(discount, offlineHandleEvent.getOfflineReason(), sysUserId);
        //发送活动下架提醒给商家
        NotifyTemplateParam shopParam = new NotifyTemplateParam();
        shopParam.setShopId(discount.getShopId());
        shopParam.setActivityId(discount.getDiscountId());
        shopParam.setActivityName(discount.getDiscountName());
        shopParam.setSendType(SendType.ACTIVITY_OFFLINE.getValue());
        eventPublisher.publishEvent(new SendMessageEvent(shopParam));
        // 移除缓存
        discountService.removeDiscountAndItemAndProdCacheById(discount.getDiscountId());
        discountService.removeDiscountsAndItemsCacheByShopId(discount.getShopId());
        return ServerResponseEntity.success();
    }

    @DeleteMapping("/{discountId}")
    @Operation(summary =  "根据活动id删除促销活动信息")
    @Parameter(name = "discountId", description = "活动ID", required = true)
    @PreAuthorize("@pms.hasPermission('platform:discount:delete')")
    public ServerResponseEntity<Void> delete(@PathVariable Long discountId) {
        Discount discount = discountService.getDiscountAndItemAndProdById(discountId);
        if (discount == null) {
            // 未找到该活动信息
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        discountService.deleteDiscountsAndItemsAndProds(discountId, discount.getShopId());
        return ServerResponseEntity.success();
    }

    @GetMapping("/getOfflineHandleEventByDiscountId/{discountId}")
    @Operation(summary =  "根据活动id获取下线信息")
    @Parameter(name = "discountId", description = "活动ID", required = true)
    @PreAuthorize("@pms.hasPermission('platform:discount:info')")
    public ServerResponseEntity<OfflineHandleEvent> getOfflineHandleEventByDiscountId(@PathVariable("discountId") Long discountId) {
        OfflineHandleEvent offlineHandleEvent = offlineHandleEventService.getProcessingEventByHandleTypeAndHandleId(OfflineHandleEventType.DISCOUNT.getValue(), discountId);
        return ServerResponseEntity.success(offlineHandleEvent);
    }

    @PostMapping("/auditDiscount")
    @PreAuthorize("@pms.hasPermission('platform:discount:update')")
    @Operation(summary =  "审核活动")
    public ServerResponseEntity<Void> auditDiscount(@RequestBody OfflineHandleEventAuditParam offlineHandleEventAuditParam) {
        Long sysUserId = SecurityUtils.getSysUser().getUserId();
        Discount discount = discountService.getDiscountAndItemAndProdById(offlineHandleEventAuditParam.getHandleId());
        if (discount == null) {
            // 未找到该活动信息
            throw new YamiShopBindException("yami.activity.cannot.find");
        }
        discountService.auditDiscount(offlineHandleEventAuditParam, sysUserId);
        //发送活动审核提醒给商家
        NotifyTemplateParam shopParam = new NotifyTemplateParam();
        shopParam.setShopId(discount.getShopId());
        shopParam.setActivityId(discount.getDiscountId());
        shopParam.setActivityName(discount.getDiscountName());
        shopParam.setSendType(SendType.ACTIVITY_AUDIT.getValue());
        eventPublisher.publishEvent(new SendMessageEvent(shopParam));
        // 移除缓存
        discountService.removeDiscountAndItemAndProdCacheById(discount.getDiscountId());
        discountService.removeDiscountsAndItemsCacheByShopId(discount.getShopId());
        return ServerResponseEntity.success();
    }
}
